<template>
  <view class="py-12">
    <BasicsForm @register="handleRegister" />
  </view>
</template>

<script setup lang="ts">
  import BasicsForm from '@/components/Form/BasicsForm.vue';
  import { useForm } from '@/components/Form';
  import { serviceTicketFormAdd } from '@/api/serviceForm';
  import { type PropType } from 'vue';
  import type { ServiceTicketFormTemplateDetailResult } from '@/api/serviceForm/types';

  const props = defineProps({
    details: Object as PropType<ServiceTicketFormTemplateDetailResult>,
  });

  const [register, { validate, setFieldsValue }] = useForm({
    labelAlign: 'left',
    validateTrigger: 'bind',
    schemas: [
      {
        label: '表单名称',
        field: 'title',
        component: 'InputTextArea',
        componentProps: {
          maxlength: 100,
          showWordLimit: true,
          placeholder: '例如服务表单',
        },
        required: true
      },
      {
        label: '表单说明',
        field: 'details',
        component: 'InputTextArea',
        componentProps: {
          placeholder: '可以描述介绍表单收集背景等',
          maxlength: 300,
          showWordLimit: true,
        }
      },
    ],
  });

  function handleRegister(e: any) {
    register(e);
    if (props.details) {
      setFieldsValue({
        title: props.details?.title,
        details: props.details?.details,
      });
    }
  }

  defineExpose({
    submit: () => {
      return new Promise(async (resolve, reject) => {
        try {
          const res = await validate();
          const data = {
            serviceTicketFormId: props.details?.id,
            ...res,
          };
          const serviceTicketFormId = await serviceTicketFormAdd(data);
          resolve({ serviceTicketFormId, ...data });
        } catch (error) {
          reject();
        }
      });
    },
  });
</script>

<style scoped></style>
